package com.hmall.search.service;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClients;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ItemClients itemClients;

    @Override
    public List<String> getSuggestion(String key) {
        try {
            //准备请求
            SearchRequest request = new SearchRequest("item");
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析请求
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {

        try {
            //请求
            SearchRequest request = new SearchRequest("item");
            //发送
            buildBasicQuery(params, request);
            //获得数据解析
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //获取存放品牌key值信息的集合
            List<String> bandList = getAggByName(aggregations, "brandAgg");
            //同上
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            //添加进入集合中
            result.put("brand", bandList);
            result.put("category", categoryList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            //准备请求
            SearchRequest request = new SearchRequest("item");
            //准备DSL
            buildBasicQuery(params, request);

            //分页
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解析响应数据，包含酒店数据，距离排序
     * 最后封装PageResult返回
     *
     * @param response
     * @return
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //获取hits数据
        SearchHits hits = response.getHits();
        List<ItemDoc> itemDocList = new ArrayList<>();
        //总条数
        long value = hits.getTotalHits().value;
        for (SearchHit searchHit : hits) {
            String json = searchHit.getSourceAsString();
            ItemDoc hotelDoc = JSON.parseObject(json, ItemDoc.class);

            //解析高亮部分
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //存在高亮则提取覆盖原来的部分
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //是否name字段存在高亮部分
                HighlightField name = highlightFields.get("name");
                if (name != null) {
                    //提取替换
                    String string = name.getFragments()[0].string();
                    hotelDoc.setName(string);
                }
            }

            itemDocList.add(hotelDoc);
        }
        return new PageDTO<ItemDoc>(value, itemDocList);
    }


    /**
     * 数据聚合
     * 解析指定字段的数据集合
     *
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //注意是Terms不是Aggregations
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        //存放key的集合
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            brandList.add(keyAsString);
        }
        return brandList;
    }

    /**
     * 添加请求参数
     * 包含条件过滤，广告算分，数据聚合请求
     *
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        String key = params.getKey();
        //构建booleanQuery
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (key == null || "".equals(key)) {
            //搜索字段为空，查询所有
            //request.source().query(QueryBuilders.matchAllQuery());
            queryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            //有则准确查询all字段
            //request.source().query(QueryBuilders.matchQuery("all",key));
            queryBuilder.must(QueryBuilders.matchQuery("all", key));
            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        }
        //品牌过滤
        if (params.getBrand() != null && !"".equals(params.getBrand())) {
            queryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //分类
        if (params.getCategory() != null && !"".equals(params.getCategory())) {
            queryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //价格过滤
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()*100).lte(params.getMaxPrice()*100));
        }


        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        queryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        //设置查询信息自定义名字为XXX+Agg
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(10)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(10)
        );

//        //排序，注意：排序后无法算分，如何解决？
//        //request.source().sort("price", SortOrder.ASC);
        if (params.getSortBy() != null && !params.getSortBy().equals("default")) {
            request.source().sort(params.getSortBy(), SortOrder.ASC);
        }

        //放入请求中
        request.source().query(functionScoreQuery);
    }


    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("item", id.toString());
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            //根据信息队列传来的id，在数据库中查找数据
            Item item = itemClients.findById(id);
            com.hmall.common.pojo.ItemDoc itemDoc = new com.hmall.common.pojo.ItemDoc(item);
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            //转换json格式，注意参数定义是json，XContentType.JSON
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
